package com.nexgo.payment.action.confirmpan;

import android.support.annotation.NonNull;

import com.nexgo.common.ByteUtils;
import com.nexgo.oaf.apiv3.emv.EmvDataSourceEnum;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.api.ApiDeviceEngine;
import com.nexgo.payment.constrant.CardMode;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.TransUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by xiaox on 2017/9/26.
 */

public class ConfirmPanPresenter implements ConfirmPanContract.Presenter {
    private final Logger mLog = LoggerFactory.getLogger(ConfirmPanPresenter.class.getSimpleName());

    private final ConfirmPanContract.View mView;
    private final DataSource mRepository;
    private final TransData mTransData;
    private boolean mIsFirstTime = true;

    public ConfirmPanPresenter(@NonNull ConfirmPanContract.View view, @NonNull DataSource repository, @NonNull TransData transData) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        mTransData = checkNotNull(transData);
        mView.setPresenter(this);
    }

    @Override
    public void start() {
        if (mIsFirstTime) {
            mIsFirstTime = false;
            byte[] tlv;
            //做黑名单处理
            if (judgeBlacklist()) {
                boolean blacklist = mRepository.isBlacklist(mTransData.getPan());
                if (blacklist) {
                    mLog.debug("在黑名单内");
                    postMainThread(() -> mView.showOnBlacklist());
                    return;
                }
            }
            //纯卡不可作预授交易
            if (isPureEcCard() && TransUtils.isAuthTrans(mTransData.getTransType())) {
                postMainThread(() -> mView.showPureEcCardBanForAuth());
                return;
            }
            // FIXME: 2018/2/1 响应银联改造，根据设置参数来确定是否需要提示卡号确认
            //if (CardMode.TAP.equals(mTransData.getCardMode())) {
            if (!"1".equals(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.IS_NEED_CONFIRM_CARD_NO), "0"))) {
                mLog.debug("直接确认卡号");
                postMainThread(() -> mView.showConfirmed());
            } else {
                mLog.debug("需要手动确认卡号");
                postMainThread(() -> mView.showConfirmPan(mTransData.getPan(), mTransData.getAmount()));
            }
        }
    }

    private boolean judgeBlacklist() {
        boolean judgeBlacklist = false;
        byte[] tlv;
        if (mTransData.getCardMode() == CardMode.TAP) {
            //qpboc流程
            tlv = ApiDeviceEngine.getDefaultEmvHandler().getTlv(new byte[]{(byte) 0x9f, 0x27}, EmvDataSourceEnum.FROM_KERNEL);
            judgeBlacklist = tlv != null && tlv[0] == 0x40;
        } else if (mTransData.getCardMode() == CardMode.INSERT) {
            //接触电子现金流程
            tlv = ApiDeviceEngine.getDefaultEmvHandler().getTlv(new byte[]{(byte) 0x9f, 0x7a}, EmvDataSourceEnum.FROM_KERNEL);
            judgeBlacklist = tlv != null && tlv[0] == 0x01;
        }
        return judgeBlacklist;
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {

    }

    private boolean isPureEcCard() {
        byte[] tlv = ApiDeviceEngine.getDefaultEmvHandler().getTlv(new byte[]{(byte) 0x9f, 0x06}, EmvDataSourceEnum.FROM_KERNEL);
        return tlv != null && tlv.length >= 8 && Arrays.equals(Arrays.copyOf(tlv, 8), ByteUtils.hexString2ByteArray("A000000333010106"));
    }

    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        if (mView.isActive()) {
            runnable.run();
        }
    }
}
